//
//  MCLoginViewController.m
//  TLYL
//
//  Created by miaocai on 2017/6/1.
//  Copyright © 2017年 TLYL01. All rights reserved.
//


#import "MCGuaJiViewController.h"
#import "MCLoginViewController.h"
#import "MCWaterRippleButton.h"
#import "MCMainTabBarController.h"
#import "MCLoginModel.h"
#import "MCMineInfoModel.h"
#import "MCLotteryID.h"
#import "MCGetMerchantInfoModel.h"
#import "MCKefuViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MCFindPasswordViewController.h"
#import "MCMainNavigationController.h"
#import "MCForcedToChangePasswordViewController.h"
#import "MCGetGAModel.h"
#import "MCGetIPAdress.h"
#import "MCXianLuXuanZeViewController.h"
#import "MCHongBaoDataModel.h"
#import "MCUpdateAppModel.h"
#import "AppDelegate.h"
#import "MCTools.h"
#import "MCGetAutoCodeModel.h"

#define   MCLogin_CornerRadius  MC_REALVALUE(45)/2.0
#define   MCTextFieldBackColor   RGB(28, 32, 58)


@interface MCLoginViewController ()<UITextFieldDelegate,UIAlertViewDelegate,NSURLSessionDelegate>
#pragma mark ------ 测试代码 --------
@property (nonatomic,weak) UIView *xianLuView;
@property (nonatomic,weak) UIView *testTextFiledView;
@property (nonatomic,weak) UITextField *tf;
#pragma mark ------ 测试代码 --------
//用户名输入框
@property (nonatomic,weak) UITextField *userNameTF;
//密码输入框
@property (nonatomic,weak) UITextField *passWordTF;
//gaCode输入框
@property (nonatomic,weak) UITextField *gaCodeTF;
//图标验证码
@property (nonatomic,weak) UILabel *authCodeLab;
//图标用户名
@property (nonatomic,weak) UIImageView *imgName;
//图标密码
@property (nonatomic,weak) UIImageView *imgPsw;
//图标Ga
@property (nonatomic,weak) UIImageView *imgGaCode;
//验证码
@property (nonatomic,weak) UIImageView *imgAuthCode;

//authCodeTF二维码输入框
@property (nonatomic,strong) UITextField *authCodeTF;

//底部ScrollView
@property (nonatomic,weak) UIScrollView *baseScrollV;
//logo
@property (nonatomic,weak) UIImageView *logoImageV;

@property (nonatomic,weak) UIView *contentView;
//lineGaCodega 的下划线
@property (nonatomic,weak) UIView *gaCodeContentView;
//AuthCode 二维码的下划线
@property (nonatomic,weak) UIView *authCodeContentView;

@property (nonatomic,weak) UIView *nameContentView;

@property (nonatomic,weak) UIView *passContentView;
//登录按钮
@property (nonatomic,weak) MCWaterRippleButton *loginBtn;
//线路检测按钮
@property (nonatomic,weak) UIButton *xianLuBtn;
//记住密码按钮
@property (nonatomic,weak) UIButton *rememberBtn;

@property (nonatomic,weak) UIButton *forgetPasswordBtn;

@property (nonatomic,weak) UIButton *kefuBtn;
//挂机软件
@property (nonatomic,weak) UIButton *guajiBtn;

@property (nonatomic,strong)NSString * url;
@property (nonatomic,assign) CGFloat contentViewHeight;
@property (nonatomic,assign) CGFloat gaHeight;


@property (nonatomic,strong)MCUpdateAppModel * updateAppModel;

@property (nonatomic,strong)MCGetAutoCodeModel * getAutoCodeModel;
//loginModel登录模型的强引用
@property (nonatomic,strong) MCLoginModel *loginModel;
//gaModel的强引用
@property (nonatomic,strong) MCGetGAModel *gaModel;
//getGAmodel的数据
@property (nonatomic,strong) MCGetGAModel *getGAmodel;
//getMerchantInfoModel登录模型的强引用
@property (nonatomic,strong) MCGetMerchantInfoModel *getMerchantInfoModel;
//getMerchantInfoModel登录模型的强引用
@property (nonatomic,strong) MCMineInfoModel *mineInfoModel;


@end


@implementation MCLoginViewController

#pragma mark ------ life cycle --------
- (void)viewDidLoad {
    [super viewDidLoad];
    [self clearUserDefault];
    [self setUpUI];
    [self addNotifacation];
    [self loadGACode];
    [self checkUpdateApp];
}

- (void)clearUserDefault{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self clearUserDefault];
    [self setStatusBarBackgroundColor:RGB(29, 37, 68)];
    self.navigationController.navigationBar.hidden = YES;
    [self relayOutImgV];
    MCHongBaoDataModel * model = [MCHongBaoDataModel sharedMCHongBaoDataModel];
    [model.hongBaoMarray removeAllObjects];
    [self authAPIID];
    

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
     [self setStatusBarBackgroundColor:[RGB(29, 37, 68) colorWithAlphaComponent:0.0]];
}

- (void)dealloc{
    
    NSLog(@"MCLoginViewController ------dealloc");
}


#pragma mark -- 检测更新
//检测更新逻辑处理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) { //确认
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:self.url]];
        }
        [self exitApp];
}

- (void)exitApp{
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    
    [UIView animateWithDuration:0.4f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
    

}
//检测更新
-(void)checkUpdateApp{
    __weak __typeof(self)wself = self;
    MCUpdateAppModel * updateAppModel = [MCUpdateAppModel sharedMCUpdateAppModel];
    updateAppModel.DownloadUrl=@"";
    _updateAppModel=updateAppModel;
    
    [updateAppModel refreashDataAndShow];
    
    updateAppModel.callBackSuccessBlock = ^(id manager) {
        
        NSDictionary * dic = manager;
        if (dic[@"DownloadUrl"]) {
            NSString * url = [NSString stringWithFormat:@"%@",dic[@"DownloadUrl"]];
            wself.updateAppModel.DownloadUrl=url;
            wself.url=url;
            if (url.length>0) {
                //有更新
                [wself openUpdate:url];
            }
        }
        
    };
    
    updateAppModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
        
    };
    
}
//检测更新弹框
-(void)openUpdate:(NSString *)url{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发现新版本，请更新！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.delegate=self;
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
    
}





#pragma mark ------ UI --------
- (void)setUpUI{
    
    //抖动时的背景色
    self.view.backgroundColor = RGB(6, 34, 50);
    UIScrollView *baseScrolV = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:baseScrolV];
    self.baseScrollV = baseScrolV;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEndEditing)];
    [baseScrolV addGestureRecognizer:tap];
    
    /*
     * base IMGV
     */
    
    UIImageView *logoBaseImageV = [[UIImageView alloc] initWithFrame:self.view.bounds];
    logoBaseImageV.backgroundColor=RGB(31, 37, 69);
    [self.baseScrollV addSubview:logoBaseImageV];
    logoBaseImageV.userInteractionEnabled = YES;
    //kxyl 的图标logo
    UIImageView *logoImageV = [[UIImageView alloc] init];
    logoImageV.image = [UIImage imageNamed:@"LOGO"];
    [logoBaseImageV addSubview:logoImageV];
    self.logoImageV = logoImageV;
    [logoImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logoBaseImageV.mas_top).offset(MC_REALVALUE(60));
        make.centerX.equalTo(self.view);
        make.height.equalTo(@(MC_REALVALUE(105)));
        make.width.equalTo(@(MC_REALVALUE(102)));
        
    }];
    
    
     self.gaHeight = 0;
   
    UIView *contentView = [[UIView alloc] init];
    [logoBaseImageV addSubview:contentView];
    self.contentView = contentView;
    contentView.backgroundColor = [UIColor clearColor];
    self.contentViewHeight = MC_REALVALUE(45*3 + 12 *2);
    /*
     *  姓名
     */
    UIView *nameContentView = [[UIView alloc] init];
    [contentView addSubview:nameContentView];
    nameContentView.backgroundColor = MCTextFieldBackColor;
    self.nameContentView = nameContentView;
    nameContentView.layer.cornerRadius = MCLogin_CornerRadius;
    nameContentView.clipsToBounds = YES;
    
    UITextField *userNameTF = [[UITextField alloc] init];
    [nameContentView addSubview:userNameTF];
    userNameTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName : RGB(181, 181, 181),NSFontAttributeName : [UIFont systemFontOfSize:MC_REALVALUE(12)]}];
    userNameTF.font = [UIFont systemFontOfSize:MC_REALVALUE(12)];
    userNameTF.delegate = self;
    userNameTF.autocorrectionType = UITextAutocorrectionTypeNo;
    userNameTF.textColor = RGB(255, 210, 0);
    self.userNameTF = userNameTF;
    [userNameTF addTarget:self action:@selector(userNameHasChanged:) forControlEvents:UIControlEventEditingChanged];
    
    UIImageView *imgName = [[UIImageView alloc] init];
    [nameContentView addSubview:imgName];
    imgName.image = [UIImage imageNamed:@"user-icon"];
    self.imgName = imgName;
    
    
    
    /*
     *  密码
     */
    UIView *passContentView = [[UIView alloc] init];
    [contentView addSubview:passContentView];
    passContentView.layer.cornerRadius = MCLogin_CornerRadius;
    passContentView.clipsToBounds = YES;
    passContentView.backgroundColor = MCTextFieldBackColor;
    self.passContentView = passContentView;
    
    UITextField *passWordTF = [[UITextField alloc] init];
    [passContentView addSubview:passWordTF];
    passWordTF.font = [UIFont systemFontOfSize:MC_REALVALUE(12)];
    passWordTF.autocorrectionType = UITextAutocorrectionTypeNo;
    passWordTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName : RGB(181, 181, 181),NSFontAttributeName : [UIFont systemFontOfSize:MC_REALVALUE(12)]}];
    passWordTF.textColor = RGB(255, 210, 0);
    passWordTF.secureTextEntry = YES;
    self.passWordTF = passWordTF;
    [passWordTF addTarget:self action:@selector(pswNameHasChanged:) forControlEvents:UIControlEventEditingDidBegin];
    [passWordTF addTarget:self action:@selector(relayOutImgV) forControlEvents:UIControlEventEditingChanged];
    
    UIImageView *imgPsw = [[UIImageView alloc] init];
    baseScrolV.backgroundColor = [UIColor whiteColor];
    [passContentView addSubview:imgPsw];
    imgPsw.image = [UIImage imageNamed:@"lock-icon"];
    self.imgPsw = imgPsw;
    
    
    /*
     *  GaCode
     */
    
    UIView *gaCodeContentView = [[UIView alloc] init];
    [contentView addSubview:gaCodeContentView];
    gaCodeContentView.backgroundColor = MCTextFieldBackColor;
    gaCodeContentView.layer.cornerRadius = MCLogin_CornerRadius;
    gaCodeContentView.clipsToBounds = YES;
    self.gaCodeContentView = gaCodeContentView;
    //GA
    UITextField *gaCodeTF = [[UITextField alloc] init];
    [gaCodeContentView addSubview:gaCodeTF];
    gaCodeTF.font = [UIFont systemFontOfSize:MC_REALVALUE(12)];
    gaCodeTF.autocorrectionType = UITextAutocorrectionTypeNo;
    gaCodeTF.delegate =self;
    gaCodeTF.textColor = RGB(255, 210, 0);
    self.gaCodeTF = gaCodeTF;
    gaCodeTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入GA验证码" attributes:@{NSForegroundColorAttributeName : RGB(181, 181, 181),NSFontAttributeName : [UIFont systemFontOfSize:MC_REALVALUE(12)]}];
    
    
    UIImageView *imgGaCode = [[UIImageView alloc] init];
    baseScrolV.backgroundColor = [UIColor whiteColor];
    [gaCodeContentView addSubview:imgGaCode];
    imgGaCode.image = [UIImage imageNamed:@"G"];
    self.imgGaCode = imgGaCode;
    
    
    UIView *authCodeContentView = [[UIView alloc] init];
    [contentView addSubview:authCodeContentView];
    authCodeContentView.backgroundColor = MCTextFieldBackColor;
    authCodeContentView.layer.cornerRadius = MCLogin_CornerRadius;
    authCodeContentView.clipsToBounds = YES;
    self.authCodeContentView = authCodeContentView;
    //authCode验证码
    UITextField *authCodeTF = [[UITextField alloc] init];
    [authCodeContentView addSubview:authCodeTF];
    authCodeTF.font = [UIFont systemFontOfSize:MC_REALVALUE(12)];
    authCodeTF.autocorrectionType = UITextAutocorrectionTypeNo;
    self.authCodeTF = authCodeTF;
    authCodeTF.textColor=RGB(255, 210, 0);
    [authCodeTF addTarget:self action:@selector(relayOutImgV) forControlEvents:UIControlEventEditingChanged];
    authCodeTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSForegroundColorAttributeName : RGB(181, 181, 181),NSFontAttributeName : [UIFont systemFontOfSize:MC_REALVALUE(12)]}];
    authCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    
    UIImageView *imgAuthCode = [[UIImageView alloc] init];
    baseScrolV.backgroundColor = [UIColor whiteColor];
    [authCodeContentView addSubview:imgAuthCode];
    imgAuthCode.image = [UIImage imageNamed:@"yanz-icon"];
    self.imgAuthCode = imgAuthCode;
    passWordTF.delegate = self;
    authCodeTF.delegate = self;
    
    //关闭自动联想
    
    [userNameTF setAutocorrectionType:UITextAutocorrectionTypeNo];
    [userNameTF setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [passWordTF setAutocorrectionType:UITextAutocorrectionTypeNo];
    [passWordTF setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [authCodeTF setAutocorrectionType:UITextAutocorrectionTypeNo];
    [authCodeTF setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [gaCodeTF setAutocorrectionType:UITextAutocorrectionTypeNo];
    [gaCodeTF setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [gaCodeTF addTarget:self action:@selector(relayOutImgV) forControlEvents:UIControlEventEditingChanged];
    
    
    /*
     *  loginBtn
     */
    MCWaterRippleButton *loginBtn = [[MCWaterRippleButton alloc] init];
    [self.view addSubview:loginBtn];
    self.loginBtn = loginBtn;
    loginBtn.layer.cornerRadius = MCLogin_CornerRadius;
    loginBtn.layer.masksToBounds = YES;
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(18)];
    [loginBtn addTarget:self action:@selector(loginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [loginBtn setTitleColor:RGB(105, 52, 10) forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"BtnBackImgV"] forState:UIControlStateNormal];
    [loginBtn setTitle:@"立即登录" forState:UIControlStateNormal];
    loginBtn.titleLabel.textColor = [UIColor whiteColor];
    loginBtn.titleLabel.font = [UIFont boldSystemFontOfSize:MC_REALVALUE(16)];
    self.loginBtn = loginBtn;
 
    
#pragma mark ------------ test------start-------------------------
    if ([testApi isEqualToString:@"testApi"]) {
        UIButton *testBtn = [[UIButton alloc] init];
        [testBtn setTitle:@"修改线路" forState:UIControlStateNormal];
        [testBtn addTarget:self action:@selector(testBtnClick:) forControlEvents:UIControlEventTouchDown];
        testBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(14)];
        [testBtn setTitleColor:RGB(45, 147, 249) forState:UIControlStateNormal];
        [baseScrolV addSubview:testBtn];
        
        [testBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.top.equalTo(self.view).offset(MC_REALVALUE(60));
            make.height.mas_equalTo(20);
        }];
    }
    
#pragma mark ------------ test------end-------------------------
    
    /*
     * authCodeLab
     */
    UILabel * authCodeLab = [[UILabel alloc]init];
    [baseScrolV addSubview:authCodeLab];
    authCodeLab.backgroundColor=RGB(214, 214, 214);
    authCodeLab.font = [UIFont boldSystemFontOfSize:20];
    authCodeLab.textColor = RGB(40, 40, 40);
    self.authCodeLab = authCodeLab;
    authCodeLab.clipsToBounds=YES;
    authCodeLab.layer.cornerRadius=5;
    authCodeLab.textAlignment=NSTextAlignmentCenter;
    authCodeLab.userInteractionEnabled = YES;
    [authCodeLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(authAPIID)]];
    
    
    /*
     *  kefuBtn
     */

    UIButton *kefuBtn = [[UIButton alloc] init];
    [kefuBtn setBackgroundImage:[UIImage imageNamed:@"kehu"] forState:UIControlStateNormal];
    kefuBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(14)];
    [kefuBtn setTitleColor:RGB(197, 215, 238) forState:UIControlStateNormal];
    [kefuBtn addTarget:self action:@selector(kefuBtnClick) forControlEvents:UIControlEventTouchDown];
    [baseScrolV addSubview:kefuBtn];
    self.kefuBtn = kefuBtn;
    
    /*
     *  guajiBtn
     */
    UIButton *guajiBtn = [[UIButton alloc] init];
    [guajiBtn setTitle:@"挂机软件" forState:UIControlStateNormal];
    guajiBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(14)];
    [guajiBtn setTitleColor:RGB(197, 215, 238) forState:UIControlStateNormal];
    [guajiBtn addTarget:self action:@selector(guajiBtnClick) forControlEvents:UIControlEventTouchDown];
    self.guajiBtn = guajiBtn;
    [baseScrolV addSubview:guajiBtn];
    
    /*
     * 线路选择
     */
    UIButton *xianLuBtn = [[UIButton alloc] init];
    [xianLuBtn setTitle:@"更换线路" forState:UIControlStateNormal];
    [xianLuBtn addTarget:self action:@selector(xianLuBtnClick:) forControlEvents:UIControlEventTouchDown];
    xianLuBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(14)];
    [xianLuBtn setTitleColor:RGB(197, 215, 238) forState:UIControlStateNormal];
    [baseScrolV addSubview:xianLuBtn];
    self.xianLuBtn = xianLuBtn;
    
    
    /*
     * 忘记密码
     */
    UIButton * forgetPasswordBtn = [[UIButton alloc]init];
    [forgetPasswordBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgetPasswordBtn addTarget:self action:@selector(FindPasswordBtnClick) forControlEvents:UIControlEventTouchDown];
    forgetPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(14)];
    [forgetPasswordBtn setTitleColor:RGB(197, 215, 238) forState:UIControlStateNormal];
    [baseScrolV addSubview:forgetPasswordBtn];
    self.forgetPasswordBtn = forgetPasswordBtn;
    
    
    
    /*
     *  记住密码
     */
   
    UIButton *rememberPswBtn = [[UIButton alloc] init];
    [baseScrolV addSubview:rememberPswBtn];
    //    RGB(255, 30, 83)
    [rememberPswBtn setTitle:@"记住密码" forState:UIControlStateNormal];
    [rememberPswBtn setTitleColor: [UIColor whiteColor]forState:UIControlStateNormal];
    [rememberPswBtn setImage:[UIImage imageNamed:@"rember_btn_normal"] forState:UIControlStateNormal];
    [rememberPswBtn setImage:[UIImage imageNamed:@"rember_btn_selected"]forState:UIControlStateSelected];
    [rememberPswBtn addTarget:self action:@selector(rememberPswBtnClick:) forControlEvents:UIControlEventTouchDown];
    rememberPswBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(14)];
    self.rememberBtn = rememberPswBtn;
    rememberPswBtn.selected = YES;

 
    //版本信息
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    UILabel *appVersionInfo = [[UILabel alloc] init];
    appVersionInfo.text = [NSString stringWithFormat:@"v%@",app_Version];
    appVersionInfo.textAlignment = NSTextAlignmentCenter;
    appVersionInfo.font = [UIFont systemFontOfSize:MC_REALVALUE(12)];
    appVersionInfo.textColor = [RGB(197, 215, 238)colorWithAlphaComponent:0.8];
    [baseScrolV addSubview:appVersionInfo];
    [appVersionInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-20);

    }];
    
    [self keyedUnarchiver];
    
}

- (void)keyedUnarchiver{
    NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[array objectAtIndex:0];
    NSString *filepath=[path stringByAppendingPathComponent:@"user.plist"];
    
    MCTools *user=[NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
    NSString *rememberStatus = user.status;
    if ([rememberStatus isEqualToString:@"Yes"] || [rememberStatus isEqualToString:@""] || rememberStatus == nil) {
        
        self.userNameTF.text = user.name;
        self.passWordTF.text = user.psw;
        
    }else{
        self.rememberBtn.selected = NO;
    }
}



#pragma mark ------ LAYOUT --------
- (void)updateViewConstraints{
    
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.equalTo(@(self.contentViewHeight));
        make.top.equalTo(self.logoImageV.mas_bottom).offset(MC_REALVALUE(18));
    }];
    [self.nameContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.logoImageV.mas_bottom).offset(MC_REALVALUE(18));
        make.left.equalTo(self.view).offset(MC_REALVALUE(33));
        make.right.equalTo(self.view).offset(-MC_REALVALUE(33));
        make.height.equalTo(@(MC_REALVALUE(45)));
    }];
    
    [self.imgName mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.nameContentView).offset(MC_REALVALUE(15));
        make.height.width.equalTo(@(MC_REALVALUE(16)));
        make.centerY.equalTo(self.nameContentView);
    }];
    
    [self.userNameTF mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imgName.mas_right).offset( MC_REALVALUE(15));
        make.right.equalTo(self.nameContentView.mas_right);
        make.centerY.equalTo(self.nameContentView);
        make.height.equalTo(self.nameContentView.mas_height);
    }];
    
    
    [self.passContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameContentView.mas_bottom).offset(MC_REALVALUE(12));
        make.left.right.equalTo(self.nameContentView);
        make.height.equalTo(@(MC_REALVALUE(45)));
    }];
    [self.imgPsw mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.passContentView).offset(MC_REALVALUE(15));
        make.height.width.equalTo(@(MC_REALVALUE(16)));
        make.centerY.equalTo(self.passContentView);
    }];
    
    [self.passWordTF mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imgPsw.mas_right).offset( MC_REALVALUE(15));
        make.right.equalTo(self.passContentView.mas_right);
        make.centerY.equalTo(self.passContentView);
        make.height.equalTo(self.passContentView.mas_height);
    }];
    
    //密码
    [self.rememberBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.authCodeContentView);
        make.height.equalTo(@(MC_REALVALUE(35)));
        make.top.equalTo(self.authCodeContentView.mas_bottom).offset(MC_REALVALUE(10));
    }];
    
    
    //忘记密码
    [self.forgetPasswordBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.loginBtn.mas_bottom).offset(MC_REALVALUE(35));
        make.height.mas_equalTo(MC_REALVALUE(20));
        make.width.mas_equalTo(MC_REALVALUE(75));
    }];
    
    //图标验证码： 后台请求的数据
    [self.authCodeLab mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.authCodeContentView);
        make.right.equalTo(self.authCodeContentView.mas_right).offset(-15);
        make.width.mas_equalTo(85);
        make.height.mas_equalTo(34);
    }];
//    self.authCodeContentView.backgroundColor = [UIColor redColor];
    [self.gaCodeContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.authCodeContentView.mas_bottom).offset(MC_REALVALUE(12));
        make.left.right.equalTo(self.nameContentView);
        make.height.equalTo(@(self.gaHeight));
    }];
    
    [self.imgGaCode mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imgName);
        make.centerY.equalTo(self.gaCodeContentView.mas_centerY);
        make.height.width.equalTo(@(MC_REALVALUE(16)));
    }];
    
    [self.gaCodeTF mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imgGaCode.mas_right).offset( MC_REALVALUE(15));
        make.right.equalTo(self.gaCodeContentView.mas_right);
        make.centerY.equalTo(self.gaCodeContentView);
        make.height.equalTo(self.gaCodeContentView.mas_height);
    }];
    
    
    [self.authCodeContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passContentView.mas_bottom).offset(MC_REALVALUE(12));
        make.left.right.equalTo(self.nameContentView);
        make.height.equalTo(@(MC_REALVALUE(45)));
    }];
    
    [self.imgAuthCode mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.imgName);
        make.centerY.equalTo(self.authCodeTF.mas_centerY);
        make.height.width.equalTo(@(MC_REALVALUE(16)));
    }];
    
    [self.authCodeTF mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imgAuthCode.mas_right).offset( MC_REALVALUE(15));
        make.right.equalTo(self.authCodeContentView.mas_right);
        make.centerY.equalTo(self.authCodeContentView);
        make.height.equalTo(self.authCodeContentView.mas_height);
    }];
    
    
    
    
    [self.loginBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.authCodeContentView.mas_left);
        make.right.equalTo(self.authCodeContentView.mas_right);
        make.top.equalTo(self.contentView.mas_bottom).offset(MC_REALVALUE(60));
        make.height.equalTo(@(45));
    }];
    //线路选择
    [self.xianLuBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.loginBtn).offset(MC_REALVALUE(0));
        make.top.equalTo(self.loginBtn.mas_bottom).offset(MC_REALVALUE(35));
        make.height.mas_equalTo(20);
    }];
    
    //客服
    [self.guajiBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_xianLuBtn);
        make.right.equalTo(self.loginBtn.mas_right).offset(0);
        make.height.mas_equalTo(20);
    }];
    
    [self.kefuBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(MC_REALVALUE(-20));
        make.top.equalTo(self.view).offset(MC_REALVALUE(56));
        make.height.mas_equalTo(MC_REALVALUE(20));
        make.width.mas_equalTo(MC_REALVALUE(75));
    }];
    
    //忘记密码
    [self.rememberBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.authCodeContentView);
        make.height.equalTo(@(MC_REALVALUE(35)));
        make.top.equalTo(self.contentView.mas_bottom).offset(MC_REALVALUE(10));
    }];
    
    
    [super updateViewConstraints];
}
+ (BOOL)requiresConstraintBasedLayout {
    return YES;
}


#pragma mark ------ touch event --------

#pragma mark --- 点击登录 -------

- (void)loginButtonClick:(UIButton *)btn{
    if ([self.userNameTF.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"用户名不能为空！"];
        return;
    }
    if ([self.passWordTF.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"密码不能为空！"];
        return;
    }
    if ([self.authCodeTF.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"验证码不能为空！"];
        return;
    }

    [self.view endEditing:YES];
    [SVProgressHUD show];
    
    MCLoginModel *loginModel = [[MCLoginModel alloc]initWithUserName:self.userNameTF.text passWord:self.passWordTF.text];
    if (![self.authCodeTF.text isEqualToString:@""]) {
        loginModel.authCode = self.authCodeTF.text;
    }
    if (![self.gaCodeTF.text isEqualToString:@""]&&self.gaCodeTF.hidden == NO) {
        loginModel.GAKey = self.getGAmodel.VerificationKey;
        loginModel.GACode = self.gaCodeTF.text;
    }
    self.loginModel = loginModel;
    
    [loginModel refreashDataAndShow];
    __weak __typeof(self)wself = self;
    
    loginModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
   
        if (manager.responseMessage != nil && ![manager.responseMessage isEqualToString:@"验证码不能为空"]) {
            [SVProgressHUD showInfoWithStatus:manager.responseMessage withComplete:^{
                [wself authAPIID];
            }];
        }
//        if (![manager.responseMessage isEqualToString:@"验证码不能为空"]) {
//            [wself performSelector:@selector(authAPIID) withObject:nil afterDelay:1];
//        }
        [wself shakeAnimationForView:wself.baseScrollV];
        
    };
    loginModel.callBackSuccessBlock = ^(ApiBaseManager *manager) {
        
        /*
         *登录成功后获取商户信息
         */
        MCGetMerchantInfoModel *model = [MCGetMerchantInfoModel sharedMCGetMerchantInfoModel];
        [model refreashDataAndShow];
        self.getMerchantInfoModel = model;
        
        /*
         *登录成功后获取用户详情
         */
        MCMineInfoModel *mineInfo_model = [MCMineInfoModel sharedMCMineInfoModel];
        self.mineInfoModel = mineInfo_model;
        [mineInfo_model refreashDataAndShow];
        mineInfo_model.callBackSuccessBlock = ^(id manager) {
            wself.mineInfoModel=[MCMineInfoModel mj_objectWithKeyValues:manager];
        };
        if (self.rememberBtn.selected) {
            
            MCTools *tools  =  [[MCTools alloc] init];
            tools.name = self.userNameTF.text;
            tools.psw = self.passWordTF.text;
            tools.status = @"Yes";
            NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *path=[array objectAtIndex:0];
            NSString *filepath=[path stringByAppendingPathComponent:@"user.plist"];
            
            [NSKeyedArchiver archiveRootObject:tools toFile:filepath];
            
        }
        
        //重新登录  我的页面布局要重新请求计算
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:MCRefreshMineDataUI];
        //登录密码为默认密码的用户，登录时缺少强制修改登录密码的功能。
        if ([wself.passWordTF.text isEqualToString:@"a123456"]) {
            MCForcedToChangePasswordViewController * vc = [[MCForcedToChangePasswordViewController alloc] init];
            vc.goBackBlock = ^{
                _gaCodeTF.text=@"";
                _passWordTF.text=@"";
                _userNameTF.text=@"";
                _authCodeTF.text=@"";
            };
            [SVProgressHUD dismiss];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController: vc];
            [wself presentViewController:nav animated:NO completion:nil];
            return ;
        }
        
        [[[UIApplication sharedApplication] keyWindow] setRootViewController:[[MCMainTabBarController alloc] init]];
        
        
        
    };
    
}


//挂机软件
- (void)guajiBtnClick{
    MCGuaJiViewController *guaJiViewController = [[MCGuaJiViewController alloc] init];
    [self presentViewController:guaJiViewController animated:YES completion:nil];
}


//用户名改变
- (void)userNameHasChanged:(UITextField *)tf{

    self.passWordTF.text = nil;
    [self relayOutImgV];
}
//密码改变
- (void)pswNameHasChanged:(UITextField *)tf{
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserNameTF"];
    if ([self.userNameTF.text isEqualToString:userName]) {
        self.passWordTF.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"Psw"];
    }
}
//记住密码
- (void)rememberPswBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    MCTools *tools  =  [[MCTools alloc] init];
    if (btn.selected) {
        tools.name = self.userNameTF.text;
        tools.psw = self.passWordTF.text;
        tools.status = @"Yes";

    } else {
        tools.name = @"";
        tools.psw = @"";
        tools.status = @"No";

    }
    NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[array objectAtIndex:0];
    NSString *filepath=[path stringByAppendingPathComponent:@"user.plist"];
    BOOL result = [NSKeyedArchiver archiveRootObject:tools toFile:filepath];
    NSLog(@"%d", result);
}



//联系客服
- (void)kefuBtnClick{
    MCKefuViewController *vc = [[MCKefuViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

/*
 * 线路检测
 */
- (void)xianLuBtnClick:(UIButton *)btn{
    
    MCXianLuXuanZeViewController * vc = [[MCXianLuXuanZeViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController: vc];
    [self presentViewController:nav animated:NO completion:nil];
    
}
//忘记密码
-(void)FindPasswordBtnClick{
    
    MCFindPasswordViewController * vc = [[MCFindPasswordViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController: vc];
    [self presentViewController:nav animated:NO completion:nil];
    
}
#pragma mark -- 关闭键盘


//关闭键盘
- (void)tapEndEditing{
    [self.view endEditing:YES];
    [BKIndicationView dismiss];
    
    
}

#pragma mark ------------ test-----start--------------------------


- (void)testxiugaiBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    self.testTextFiledView.hidden =YES;
    xianluaddr = self.tf.text;
    [[NSUserDefaults standardUserDefaults] setValue:self.tf.text forKey:@"testApi"];
    [[NSUserDefaults standardUserDefaults] setValue:self.tf.text forKey:@"BASEURL"];
    [self authAPIID];
}

- (void)testBtnClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    self.testTextFiledView.hidden =NO;
    UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(0, 20, G_SCREENWIDTH - MC_REALVALUE(50), 50)];
    [self.testTextFiledView addSubview:tf];
    tf.placeholder = @"请输入服务器地址";
    self.tf = tf;
    tf.backgroundColor = [UIColor greenColor];
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"testApi"];
    if ([str isEqualToString:@""] || str == nil) {
        self.tf.text = MCTEST_BASE_API;
    }else{
        tf.text = str;
    }
    xianluaddr = self.tf.text;
    UIButton *testxiugaiBtn = [[UIButton alloc] initWithFrame:CGRectMake(0.5 *(G_SCREENWIDTH - MC_REALVALUE(100)), 100, 100, 50)];
    testxiugaiBtn.backgroundColor = [UIColor orangeColor];
    [testxiugaiBtn setTitle:@"修改" forState:UIControlStateNormal];
    [testxiugaiBtn addTarget:self action:@selector(testxiugaiBtnClick:) forControlEvents:UIControlEventTouchDown];
    testxiugaiBtn.titleLabel.font = [UIFont systemFontOfSize:MC_REALVALUE(14)];
    [testxiugaiBtn setTitleColor:RGB(45, 147, 249) forState:UIControlStateNormal];
    [self.testTextFiledView addSubview:testxiugaiBtn];
}






#pragma mark ------ 请求数据 --------
//验证码
- (void)authAPIID{
    WS(weakSelf);

    self.authCodeLab.text = @"重试";
    MCGetAutoCodeModel * getAutoCodeModel = [[MCGetAutoCodeModel alloc] init];
    self.getAutoCodeModel = getAutoCodeModel;
    getAutoCodeModel.type = @"0";
    [getAutoCodeModel refreashDataAndShow];
    getAutoCodeModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {

    };
    getAutoCodeModel.callBackSuccessBlock = ^(id manager) {
        NSString *  verification_code = [NSString stringWithFormat:@"%@",manager[@"verification_code"]];
        weakSelf.authCodeLab.text=verification_code;
    };

}




//加载GA
- (void)loadGACode{
    
    MCGetGAModel *gaModel = [[MCGetGAModel alloc]init];
    gaModel.UserName = self.userNameTF.text;
    self.gaModel = gaModel;
    [gaModel refreashDataAndShow];
    __weak typeof(self)wself = self;
    gaModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        
    };
    gaModel.callBackSuccessBlock = ^(ApiBaseManager *manager) {
        
        wself.getGAmodel = [MCGetGAModel mj_objectWithKeyValues:manager.ResponseRawData];
        if ([wself.getGAmodel.VerificationMode containsString:@"1"]) {
            wself.contentViewHeight = MC_REALVALUE(45 * 4 + 12 *3);
            wself.gaHeight = MC_REALVALUE(45);
        } else {
            wself.contentViewHeight = MC_REALVALUE(45 * 3 + 12 *2);
            wself.gaHeight = MC_REALVALUE(0);
            
        }

        [self.view setNeedsUpdateConstraints];
    };
    
}

#pragma mark textField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [self relayOutImgV];
    
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
   
    if (textField!= self.authCodeTF) {
        [self loadGACode];
    }
    
    [self relayOutImgV];

}
#pragma mark relayOutImgV
-(void)relayOutImgV{
    if (self.userNameTF.text.length>0) {
        self.imgName.image = [UIImage imageNamed:@"user-sr-icon"];
    }else{
        self.imgName.image = [UIImage imageNamed:@"user-icon"];
    }
    
    if (self.passWordTF.text.length>0) {
        self.imgPsw.image = [UIImage imageNamed:@"lock-sr-icon"];
    }else{
        self.imgPsw.image = [UIImage imageNamed:@"lock-icon"];
    }
    
    if (self.authCodeTF.text.length>0) {
        self.imgAuthCode.image = [UIImage imageNamed:@"yanz-sr-icon"];
    }else{
        self.imgAuthCode.image = [UIImage imageNamed:@"yanz-icon"];
    }
    
    if (self.gaCodeTF.text.length>0) {
        self.imgGaCode.image = [UIImage imageNamed:@"Gz"];
    }else{
        self.imgGaCode.image = [UIImage imageNamed:@"G"];
    }
}
#pragma mark -- 键盘处理遮挡
- (void)addNotifacation{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentLoginVC) name:@"PRESENT_LOGINVC_NOTICATION" object:nil];
}
//弹出登录页的提示
- (void)presentLoginVC{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [SVProgressHUD showInfoWithStatus:@"您的登录已失效，请重新登录"];
        
    });
    
    
}

//当键弹出时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    
    if (IS_iPhoneX) {
        return;
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.baseScrollV.contentSize = CGSizeMake(G_SCREENWIDTH, G_SCREENHEIGHT + 100);
        self.baseScrollV.contentOffset = CGPointMake(0, 100);
        
        
    }];
}
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    if (IS_iPhoneX) {
        return;
    }
    self.baseScrollV.contentSize = CGSizeMake(G_SCREENWIDTH, G_SCREENHEIGHT);
    self.baseScrollV.contentOffset = CGPointMake(0,0);
}
#pragma mark ------ 改变状态栏颜色 --------
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}
#pragma mark ------ 保存数据 --------
+(NSDictionary*)returnDictionaryWithDataPath:(NSData*)data {
    
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    NSDictionary* myDictionary = [unarchiver decodeObjectForKey:@"talkData"];
    [unarchiver finishDecoding];
    return myDictionary;
}
#pragma mark 抖动动画
//抖动动画
- (void)shakeAnimationForView:(UIView *) view{
    CALayer *viewLayer = view.layer;
    
    CGPoint position = viewLayer.position;
    
    CGPoint x = CGPointMake(position.x + 5, position.y);
    
    CGPoint y = CGPointMake(position.x - 5, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    
    [animation setAutoreverses:YES];
    
    [animation setDuration:.03];
    
    [animation setRepeatCount:4];
    
    [viewLayer addAnimation:animation forKey:nil];
    
}
#pragma mark ------------ test------start-------------------------
-(UIView *)testTextFiledView{
    if (_testTextFiledView ==nil) {
        UIView *xianLuView = [[UIView alloc] initWithFrame:CGRectMake(MC_REALVALUE(25), MC_REALVALUE(261), G_SCREENWIDTH - MC_REALVALUE(50), MC_REALVALUE(165))];
        xianLuView.backgroundColor = [UIColor whiteColor];
        xianLuView.layer.cornerRadius = 6;
        xianLuView.clipsToBounds = YES;
        xianLuView.layer.borderWidth = 0.5;
        xianLuView.layer.borderColor = RGB(181, 181, 181).CGColor;
        
        [self.view addSubview:xianLuView];
        _testTextFiledView = xianLuView;
    }
    return _testTextFiledView;
}
#pragma mark ------------ test------end-------------------------

@end

